import Vue from 'vue'
import Router from 'vue-router'
import NProgress from 'nprogress'
// import permission from './permission'
import store from '../store/'
import {
  clearHttpRequestingList
} from '@http/httpRequestList'
import routes from './routes'
import {
  Message
} from 'element-ui'
Vue.$httpRequestList = []
Vue.use(Router)

const originalPush = Router.prototype.push
Router.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}
let router = new Router({
  routes
})

let permission = (to, next) => {
  next()
  // 放行主路由
  // if (to.name === 'main') {
  //   next()
  //   return
  // }

  // if (!store.state.menu.sidebarMap.main || !store.state.menu.sidebarMap.main.length) {
  //   Message(`您的菜单为空！`)
  //   next('forbidden')
  //   return
  // }
  // if (!store.state.menu.routers || !store.state.menu.routers.length) {
  //   Message(`您的路由为空！`)
  //   next('forbidden')
  //   return
  // }

  // let item = store.state.menu.routers.find(item => item.name === to.name && to.fullPath.indexOf(item.path) !== -1)
  // if (item) {
  //   // let btns = await _serverButtons(9, item.id)
  //   // store.commit('menu/SET_BUTTONS', btns.data)
  //   next()
  // } else {
  //   store.commit('menu/SET_BUTTONS', [])
  //   Message(`您没有${to.name}路由权限`)
  //   next('forbidden')
  // }
}
router.beforeEach((to, from, next) => {
  clearHttpRequestingList()
  NProgress.start()
  const whiteList = store.getters['permission/getWhiteList']

  if (whiteList.indexOf(to.name) > -1 || whiteList.indexOf(to.path) > -1) {
    next()
  } else if (!store.getters['user/getUserId'] || !store.getters['menu/getSidebarList']().main || !store.getters['menu/getSidebarList']().main.length) {
    store.dispatch('user/fetchUserInfo').then(res => {
      if (res.status) {
        // 权限校验
        store.dispatch('menu/fetchMenu', {
          appId: 56
        }).then(res => {
          if (!res.data || !res.data.length) {
            Message('您的菜单为空')
            next({
              name: 'forbidden'
            })
            return
          }
          permission(to, next)
        })
        // permission(store, routes, to, next)
      } else {
        switch (res.code) {
          case -500:
            next({
              name: 'badGateway'
            })
            break
          case 70005:
            next({
              name: 'login'
            })
            break
        }
      }
    })
  } else {
    // 权限校验
    permission(to, next)
    // permission(store, routes, to, next)
  }
})
router.afterEach(() => {
  NProgress.done()
})
export default router
